from zope.interface import Interface
from zope.interface import implements
from Acquisition import aq_inner
from zope.component import getMultiAdapter
from Products.CMFCore.utils import getToolByName

from plone.app.portlets.portlets import base
from plone.portlets.interfaces import IPortletDataProvider

from zope import schema
from zope.formlib import form
from plone.memoize.instance import memoize
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from my315ok.xtinfocontent.interfaces import Ibloodbank


from my315ok.xtinfocontent import xtinfocontentMessageFactory as _
from plone.portlet.collection import PloneMessageFactory as _a
from my315ok.portlet.rollitems import RollPortletMessageFactory as _r

class Ibloodbankportlet(IPortletDataProvider):
    """A portlet

    It inherits from IPortletDataProvider because for this portlet, the
    data that is being rendered and the portlet assignment itself are the
    same.
    """

    # TODO: Add any zope.schema fields here to capture portlet configuration
    # information. Alternatively, if there are no settings, leave this as an
    # empty interface - see also notes around the add form and edit form
    # below.

    # some_field = schema.TextLine(title=_(u"Some field"),
    #                              description=_(u"A field to use"),
    #                              required=True)
    name = schema.TextLine(
           title=_(u"info_title"),
           description=_(u"specify title of the portlet "),
           default=u"",
           required=False)
    topid = schema.TextLine(title=_r(u"top id"),
                             description=_r(u"the wraped top id of the roll zone"),
                             required=True)
    cssid = schema.TextLine(title=_r(u"css id"),
                             description=_r(u"the css id of the roll zone"),
                             required=True)

    limit = schema.Int(title=_a(u"Limit"),
                       description=_a(u"Specify the maximum number of items to show in the portlet. "
                                       "Leave this blank to show all items."),
                       required=False)
    wordsnum = schema.Int(title=_(u"number"),
                       description=_(u"Specify the maximum number of words to show as title. "
                                       "Leave this blank to show all items."),
                       default=36,
                       required=False)
    roll_direc = schema.Choice(
        title=_r(u"direction"),
        description=_r(u"Choose the roll direction"),
        vocabulary = 'rollitems.RollDirectionVocabulary' )
    
    speed = schema.Int(title=_r(u"speed"),
                       description=_r(u"Specify the speed of the roll items "),                                      
                       required=True)
    pause = schema.Int(title=_r(u"pause time"),
                       description=_(u"Specify the time of pause(ms)"),
                       required=True)
    step = schema.Int(title=_r(u"step length"),
                       description=_r(u"Specify the step length of every move."),
                       required=True)


class Assignment(base.Assignment):
    """Portlet assignment.

    This is what is actually managed through the portlets UI and associated
    with columns.
    """

    implements(Ibloodbankportlet)

    name = u""
    topid = None
    cssid = None
    limit= 1
    wordsnum = 36
    roll_direc = "up"
    speed = 30
    pause = 1000
    step = 1

    # TODO: Add keyword parameters for configurable parameters here
    def __init__(self, name=u'',topid=None,cssid=None,limit=1,wordsnum=36,roll_direc="up",speed=30,pause=1000,step=1):
        self.name = name
        self.topid = topid
        self.cssid = cssid
        self.limit = limit
        self.wordsnum = wordsnum
        self.roll_direc = roll_direc
        self.speed = speed
        self.step = step
        



    @property
    def title(self):
        """This property is used to give the title of the portlet in the
        "manage portlets" screen.
        """
        return _(u"BloodbankInfo")


class Renderer(base.Renderer):
    """Portlet renderer.

    This is registered in configure.zcml. The referenced page template is
    rendered, and the implicit variable 'view' will refer to an instance
    of this class. Other methods can be added and referenced in the template.
    """

    render = ViewPageTemplateFile('bloodbank.pt')
    
    def cropTitle(self,text, length, ellipsis='...'):
        if length == 0 or length == None:
            return text
        context = aq_inner(self.context)
        pview = getMultiAdapter((context,self.request),name=u"plone")
#        pview = getMultiAdapter((self.parent(), self.request), name=u'earthqk_event_view')
        croped = pview.cropText(text, length)
        return croped
    def toLocalizedTime(self, time, date_only=None, time_only=None):
        """Convert time to localized time
        """
        fmt = '%Y/%m/%d %H:%M:%S'
        datefmt = '%Y/%m/%d'
        timefmt  = '%H:%M:%S'
        if date_only:
            date = time.strftime(datefmt)
            return date
        elif time_only:
            time = time.strftime(timefmt)
            return time
        else:
            tmp = time.strftime(fmt)
            return tmp
        
    @memoize
    def results(self):
#        import pdb
#        pdb.set_trace()
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')        
        lm = self.data.limit
        num = self.data.wordsnum
        result = []
        if lm > 0:
            brains = catalog(object_provides=Ibloodbank.__identifier__,
                             review_status='published',
                             sort="modified",
                             sort_order='reverse',
                             sort_limit=lm)[:lm]
        else:
            brains = catalog(object_provides=Ibloodbank.__identifier__,
                             review_status='published',
                             sort="modified",
                             sort_order='reverse')
                           
            
                        
        item={}
        for brain in brains:
            bn = brain.category                                     
            item["url"] = brain.getURL()
            tl = brain.getObject().getText()
            tl = self.cropTitle(tl, num)
            item["text"] = tl
            item["modified"] = self.toLocalizedTime(brain.modified, date_only=True)
            result.append(item)
            item={}
        return result
        
    @memoize
    def render_marqueejs(self):      
        cssid = self.data.cssid
       
        out="""jq(document).ready(function(){
        rolltext(".%(mid)s");    
});""" % dict(mid=cssid)
        return out  



# NOTE: If this portlet does not have any configurable parameters, you can
# inherit from NullAddForm and remove the form_fields variable.

class AddForm(base.AddForm):
    """Portlet add form.

    This is registered in configure.zcml. The form_fields variable tells
    zope.formlib which fields to display. The create() method actually
    constructs the assignment that is being added.
    """
    form_fields = form.Fields(Ibloodbankportlet)

    def create(self, data):
        return Assignment(**data)


# NOTE: IF this portlet does not have any configurable parameters, you can
# remove this class definition and delete the editview attribute from the
# <plone:portlet /> registration in configure.zcml

class EditForm(base.EditForm):
    """Portlet edit form.

    This is registered with configure.zcml. The form_fields variable tells
    zope.formlib which fields to display.
    """
    form_fields = form.Fields(Ibloodbankportlet)
